import React, { useEffect, useState } from 'react';
import { Select, Checkbox } from 'antd';
import { CaretDownOutlined } from '#/utils/antdIcons';
import { TRDefault } from '@/components/index.js';
import type { IOption } from '../../type';
import styles from './index.less';

interface IProps {
  /**
   * 选择事件
   */

  onChange?: (values: string[]) => void;
  /**
   * 选择值
   */
  value?: string[];
  /**
   * 选项
   */
  options?: IOption[];
  /**
   * 占位符
   */
  placeholder?: string;
  /**
   * 最多显示几个标签
   */
  maxTagCount?: number;
  /**
   * 是否显示下拉小箭头
   */
  showArrow?: boolean;
  /**
   * 最长显示
   */
  maxTagTextLength?: number;

  /**
   * 是否显示全选
   */
  isShowSelectAll?: boolean;
  /**
   * logo
   */
  logo?: React.ReactNode;
}

const BaseSelect = (props: IProps) => {
  const {
    onChange,
    value,
    options,
    isShowSelectAll = true,
    logo = <CaretDownOutlined />,
    placeholder,
    ...rest
  } = props;
  const [checkedList, setCheckedList] = useState<string[]>([]);
  const [indeterminate, setIndeterminate] = useState(true);
  const [showOptions, setShowOptions] = useState<IOption[]>(options || []);
  const [originOptions, setOriginOptions] = useState<IOption[]>(options || []);
  const [personSearch, setPersonSearch] = useState<string>('');
  const [checkAll, setCheckAll] = useState(false);

  // 根据传入的value值组装数据
  const getOriginOptions = (list: IOption[], arr: string[], checked: boolean) => {
    let _arr: any = [];
    if (arr.length > 0) {
      list.forEach((item: IOption) => {
        let obj = item;
        arr.forEach((i) => {
          if (item.value === i) {
            obj = { ...item, checked };
          }
        });
        _arr = [..._arr, obj];
      });
      return _arr;
    } else {
      return list;
    }
  };

  // 获取搜索数据
  const getSearchData = (keyWord: string, arr: IOption[]) => {
    const list: IOption[] = arr.filter((item: IOption) => {
      return item?.label?.indexOf(keyWord) >= 0;
    });
    return list;
  };

  // 搜索
  const onSearch = (keyWords: string) => {
    const _showOptions = getSearchData(keyWords, originOptions || []);
    setShowOptions(_showOptions);
    setPersonSearch(keyWords);
    const _checkedList: any[] =
      _showOptions.filter((item) => item?.checked)?.map((item) => item.value) || [];
    setIndeterminate(
      !!_checkedList?.length &&
        !!_showOptions?.length &&
        _checkedList?.length < _showOptions?.length,
    );
    if (!!_checkedList?.length && _checkedList?.length === _showOptions?.length) {
      setCheckAll(true);
    } else {
      setCheckAll(false);
    }
  };

  // 选择
  const _onChange = (e: any) => {
    const _checked = e.target.checked;
    const _value = e.target.value;
    let list: IOption[] = [];
    const _originOptions =
      originOptions?.map((item) => {
        if (item.value === _value) {
          return { ...item, checked: _checked };
        } else {
          return item;
        }
      }) || [];
    list = _originOptions;
    const _checkedList: any[] =
      list.filter((item) => item?.checked)?.map((item) => item.value) || [];
    setShowOptions(_originOptions);
    setOriginOptions(_originOptions);
    setCheckedList(_checkedList);
    setPersonSearch('');
    setIndeterminate(
      !!_checkedList?.length &&
        !!_originOptions?.length &&
        _checkedList?.length < _originOptions?.length,
    );
    if (!!_checkedList?.length && _checkedList?.length === _originOptions?.length) {
      setCheckAll(true);
    } else {
      setCheckAll(false);
    }
    onChange && onChange(_checkedList);
  };

  // 全选
  const _onCheckAllChange = (e: any) => {
    const _checked = e.target.checked;
    let _checkedList: any[] = showOptions?.map((item: IOption) => item.value) || [];
    let _originOptions: IOption[] = [];
    let list: IOption[] = [];
    if (_checked) {
      _originOptions = getOriginOptions(originOptions || [], _checkedList, true);
    } else {
      _originOptions = getOriginOptions(originOptions || [], _checkedList, false);
    }
    list = _originOptions;
    _checkedList = list.filter((item) => item?.checked)?.map((item: IOption) => item.value) || [];
    setShowOptions(_originOptions);
    setOriginOptions(_originOptions);
    setCheckedList(_checkedList);
    setPersonSearch('');
    setIndeterminate(
      !!_checkedList?.length &&
        !!_originOptions?.length &&
        _checkedList?.length < _originOptions?.length,
    );
    if (!!_checkedList?.length && _checkedList?.length === _originOptions?.length) {
      setCheckAll(true);
    } else {
      setCheckAll(false);
    }
    onChange && onChange(_checkedList);
  };

  const onBlur = () => {
    if (!personSearch) {
      const _checkedList: any[] =
        originOptions.filter((item) => item?.checked)?.map((item: IOption) => item.value) || [];
      setShowOptions(originOptions);
      setCheckedList(_checkedList);
      setPersonSearch('');
      onChange && onChange(_checkedList);
    }
  };

  useEffect(() => {
    if (value && options) {
      const arr = getOriginOptions(options, value, true);
      setCheckedList(value);
      setOriginOptions(arr);
      setShowOptions(arr);
      setIndeterminate(!!value?.length && !!arr?.length && value?.length < arr?.length);
      if (!!value?.length && value?.length === arr?.length) {
        setCheckAll(true);
      } else {
        setCheckAll(false);
      }
    }
  }, [value, options]);

  return (
    <Select
      // mode={
      //   isShowSelectAll && checkedList?.length === originOptions?.length ? undefined : 'multiple'
      // }
      dropdownClassName={styles.dropdown}
      suffixIcon={logo}
      showSearch={true}
      searchValue={personSearch}
      // value={
      //   checkedList?.length === originOptions?.length && isShowSelectAll ? '全部' : checkedList
      // }
      value={
        !checkedList.length
          ? placeholder
          : checkedList.length === originOptions.length && isShowSelectAll
          ? '全部'
          : `${checkedList.length}项/${originOptions.length}项`
      }
      options={showOptions}
      onSearch={(e) => {
        onSearch(e);
      }}
      onBlur={onBlur}
      onChange={onChange}
      dropdownRender={() => {
        return (
          <>
            {isShowSelectAll && showOptions?.length > 0 ? (
              <Checkbox
                indeterminate={indeterminate}
                onChange={(e) => _onCheckAllChange(e)}
                checked={checkAll}
              >
                全选
              </Checkbox>
            ) : null}
            {showOptions?.length > 0 ? (
              showOptions?.map((item: IOption, idx: number) => {
                return (
                  <Checkbox
                    key={idx}
                    value={item.value}
                    checked={item.checked}
                    className={styles.checkBox}
                    onChange={(e) => _onChange(e)}
                  >
                    {item.label}
                  </Checkbox>
                );
              })
            ) : (
              <TRDefault type={'emptysm'} message={'暂无数据'} />
            )}
          </>
        );
      }}
      {...rest}
    />
  );
};

export default BaseSelect;
